<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/7/31
 * Time: 13:43
 */

namespace common\models\Service;


use common\models\CommonFunction;
use common\models\DAO\DayAccrual;
use common\models\DAO\HongbaoSend;
use common\models\DAO\HongbaoSendAccrual;
use common\models\DAO\HongbaoSendList;
use common\models\DAO\TeamBrokerage;
use common\models\DAO\User;
use common\models\DAO\UserHongbao;
use common\models\DAO\UserHongbaoUseList;
use common\models\DAO\UserWalletLog;
use common\msg\UserMsg;

class SendService {
    public static function deal_accrual($param){
        $amount = intval($param['amount']);
        $userID = $param['userID'];
        $money = floatval($param['money']) * 100;
        $result['status'] = 0;
        $result['msg'] = UserMsg::$time_out;
        $remainder = 0;
        $user_hongbao = UserHongbao::findOne($userID);
        if($user_hongbao)
            $remainder = intval($user_hongbao['money']);
        $use_money = $amount * $money;
        $accrual = 0;
        if($use_money > $remainder){
            $accrual = $use_money - $remainder;
            $hongbao = $remainder;
        }else
            $hongbao = $use_money;
        $now = time();
        $transaction = \Yii::$app->db->beginTransaction();
        $user_hongbao->money = $remainder - $hongbao;
        $hb_result = $user_hongbao->save();
        if(!$hb_result){
            $transaction->rollBack();
            return $result;
        }
        $hb_use = new UserHongbaoUseList();
        $hb_use->userID = $userID;
        $hb_use->hongBao = $hongbao;
        $hb_use->createTime = $now;
        $hb_use->type = 2;
        $hb_use_result = $hb_use->save();
        if(!$hb_use_result){
            $transaction->rollBack();
            return $result;
        }


        $send = new HongbaoSend();
        $send->userID = $userID;
        $send->money = $money;
        $send->amount = $amount;
        $send->createTime = $now;
        $send->accrual = $accrual;
        $send_result = $send->save();
        if(!$send_result){
            $transaction->rollBack();
            return $result;
        }
        $sendID = $send->id;
        //扣除钱包余额
        if($accrual > 0){
            $wallet_reminder = Wallet::remainder($userID);
            if($wallet_reminder < $accrual){
                $transaction->rollBack();
                $result['msg'] = '钱包余额不足！是否充值？';
                $result['status'] = 2;
                return $result;
            }
            //更新用户余额 - 扣除账户余额
            $accrual_total = DayAccrual::find()->where(array('userID'=>$userID))->andFilterWhere(['>', 'money', 0])->orderBy('date asc')->all();
            $init_money = $accrual;
            //钱包明细
            $typeID = 5;
            $user_wallet = new UserWalletLog();
            $user_wallet->type = 2;
            $user_wallet->money = $accrual;
            $user_wallet->createTime = $now;
            $user_wallet->userID = $userID;
            $user_wallet->road = $typeID;
            $user_wallet->desc = '发红包';
            $user_wallet_result  = $user_wallet->save();
            if(!$user_wallet_result){
                $transaction->rollBack();
                return $result;
            }

            foreach($accrual_total as $v){
                $money = intval($v['money']);
                $id = $v['id'];
                if($money <= 0)
                    continue;
                if($money < $init_money){
                    $accrual_one = DayAccrual::findOne($id);
                    $accrual_one->money = 0;
                    $accrual_one->updateTime = $now;
                    $one_result = $accrual_one->save();
                    if(!$one_result){
                        $transaction->rollBack();
                        return $result;
                    }
                    $send_accrual = new HongbaoSendAccrual();
                    $send_accrual->userID = $userID;
                    $send_accrual->money = $money;
                    $send_accrual->createTime = $now;
                    $send_accrual->accrualID = $id;
                    $send_accrual->sendID = $sendID;
                    $list_result = $send_accrual->save();
                    if(!$list_result){
                        $transaction->rollBack();
                        return $result;
                    }
                    $init_money = $init_money - $money;
                }else{
                    $accrual_one = DayAccrual::findOne($id);
                    $accrual_one->money = $money - $init_money;
                    $accrual_one->updateTime = $now;
                    $one_result = $accrual_one->save();
                    if(!$one_result){
                        $transaction->rollBack();
                        return $result;
                    }
                    $send_accrual = new HongbaoSendAccrual();
                    $send_accrual->userID = $userID;
                    $send_accrual->money = $init_money;
                    $send_accrual->createTime = $now;
                    $send_accrual->accrualID = $id;
                    $send_accrual->sendID = $sendID;
                    $list_result = $send_accrual->save();
                    if(!$list_result){
                        $transaction->rollBack();
                        return $result;
                    }
                    break;
                }
            }
        }
        $transaction->commit();
        $random = CommonFunction::getRandChar(6);
        $en_userID = $random.$userID;
        return ['status'=>1,'base'=>\Yii::$app->urlManager->createUrl(['open/index', 'id' => $send->id, 'scyd_user'=>$en_userID]), 'url'=>\Yii::$app->urlManager->createAbsoluteUrl(['open/index', 'id' => $send->id, 'scyd_user'=>$en_userID])];
    }

    public static function deal($param){
        $amount = intval($param['amount']);
        $userID = $param['userID'];
        $money = floatval($param['money']) * 100;
        $result['status'] = 0;
        $result['msg'] = UserMsg::$time_out;
        $remainder = 0;
        $user_hongbao = UserHongbao::findOne($userID);
        if($user_hongbao)
            $remainder = intval($user_hongbao['money']);
        $use_money = $amount * $money;
        if($use_money > $remainder){
            $result['msg'] = UserMsg::$no_hongbao;
            return $result;
        }
        $now = time();
        $transaction = \Yii::$app->db->beginTransaction();
        $user_hongbao->money = $remainder - $use_money;
        $hb_result = $user_hongbao->save();

        if(!$hb_result){
            $transaction->rollBack();
            return $result;
        }
        $hb_use = new UserHongbaoUseList();
        $hb_use->userID = $userID;
        $hb_use->hongBao = $use_money;
        $hb_use->createTime = $now;
        $hb_use->type = 2;
        $hb_use_result = $hb_use->save();
        if(!$hb_use_result){
            $transaction->rollBack();
            return $result;
        }
        $send = new HongbaoSend();
        $send->userID = $userID;
        $send->money = $money;
        $send->amount = $amount;
        $send->createTime = $now;
        $send_result = $send->save();
        if(!$send_result){
            $transaction->rollBack();
            return $result;
        }
        $transaction->commit();
        $random = CommonFunction::getRandChar(6);
        $en_userID = $random.$userID;
        return ['status'=>1, 'base'=>\Yii::$app->urlManager->createUrl(['open/index', 'id' => $send->id, 'scyd_user'=>$en_userID]), 'url'=>\Yii::$app->urlManager->createAbsoluteUrl(['open/index', 'id' => $send->id, 'scyd_user'=>$en_userID])];
    }

    public static function hb_deal($param){
        $userID = $param['userID'];
        $money = $param['money'] * $param['amount'];
        $result['status'] = 0;
        $result['msg'] = UserMsg::$time_out;
        $remainder = 0;
        $user_hongbao = UserHongbao::findOne($userID);
        if($user_hongbao)
            $remainder = intval($user_hongbao['money']);
        if($money > $remainder){
            $result['msg'] = UserMsg::$no_hongbao;
            return $result;
        }
        $now = time();
        $transaction = \Yii::$app->db->beginTransaction();
        $user_hongbao->money = $remainder - $money;
        $hb_result = $user_hongbao->save();

        if(!$hb_result){
            $transaction->rollBack();
            return $result;
        }
        $hb_use = new UserHongbaoUseList();
        $hb_use->userID = $userID;
        $hb_use->hongBao = $money;
        $hb_use->createTime = $now;
        $hb_use->type = 2;
        $hb_use_result = $hb_use->save();
        if(!$hb_use_result){
            $transaction->rollBack();
            return $result;
        }
        $send = new HongbaoSend();
        $send->userID = $userID;
        $send->money = $param['money'];
        $send->amount = $param['amount'];
        $send->createTime = $now;
        $send_result = $send->save();
        if(!$send_result){
            $transaction->rollBack();
            return $result;
        }
        $transaction->commit();
        return ['status'=>1, 'url'=>\Yii::$app->urlManager->createUrl(['open/index', 'id' => $send->id])];
    }

    public static function check($userID, $id){
        $send = HongbaoSend::findOne($id);
        if(!$send) return false;

        $list = HongbaoSendList::findOne(['userID'=>$userID, 'sendID'=>$id]);
        if($list) return true;

        if(intval($send['use']) >= intval($send['amount']))
            return ['over'=>1];
        $sendUserID = $send['userID'];
        $send_userInfo = User::findOne($sendUserID);
        if(!$send_userInfo) return false;
        $result['avatar'] = $send_userInfo['avatar'];
        $result['phone'] = CommonFunction::dealTel(CommonFunction::decrypt($send_userInfo['phone']));
        return $result;

    }

    //新手领取红包动作
    public static function get_new($userInfo, $id){
        $error['status'] = 0;
        $error['msg'] = UserMsg::$time_out;
        $userID = $userInfo['userID'];
        $send = HongbaoSend::findOne($id);
        $money = $send['money'];
        if(!$send) return $error;
        if(intval($send->use) >= $send->amount){
            $error['msg'] = UserMsg::$over_hongbao;
            return $error;
        }
        $status = HongbaoSendList::findOne(['userID'=>$userID, 'sendID'=>$id]);
        if($status){
            $error['msg'] = UserMsg::$alread_hongbao;
            return $error;
        }
        $send->use = intval($send->use) + 1;
        $send_result = $send->save();
        if(!$send_result) return $error;

        $date = date('Ymd');
        $now = time();
        $sendList_model = new HongbaoSendList();
        $sendList_model->sendID = $send->id;
        $sendList_model->sendUserID = $send->userID;
        $sendList_model->money = $send->money;
        $sendList_model->userID = $userID;
        $sendList_model->createTime = $now;
        $sendList_result = $sendList_model->save();
        if(!$sendList_result) return $error;
        $dayAccrual = new DayAccrual();
        $dayAccrual->userID = $userID;
        $dayAccrual->date = $date;
        $dayAccrual->money = $money;
        $dayAccrual->invest = $money;
        $dayAccrual->createTime = $now;
        $dayAccrual->updateTime = $now;
        $dayAccrual->sendID = $send->id;
        $accrual_result = $dayAccrual->save();
        if(!$accrual_result) return $error;

        $user_wallet = new UserWalletLog();
        //钱包明细
        $user_wallet->type = 9;
        $user_wallet->money = $money;
        $user_wallet->createTime = $now;
        $user_wallet->userID = $userID;
        $user_wallet->road = 1;
        $user_wallet->desc = '领取红包';
        $user_wallet_result = $user_wallet->save();
        if(!$user_wallet_result) return $error;
        if(!empty($userInfo['recID']) && !empty($userInfo['tel'])){
            $rec_info = User::findOne($userInfo['recID']);
            if(!empty($rec_info['openID']))
                SendWxMessage::hongbao($rec_info['openID'], '-'.CommonFunction::formatMoney($money).'元', '您的好友'.CommonFunction::dealTel($userInfo['tel']).'领取了您的'.CommonFunction::formatMoney($money).'元红包。');
        }
       /* if(!empty($userInfo['recID']) && !empty($userInfo['tel'])){

            $rec_info = User::findOne($userInfo['recID']);
            if($rec_info){
                $dayAccrual = new DayAccrual();
                $dayAccrual->userID = $rec_info['id'];
                $dayAccrual->date = $date;
                $dayAccrual->money = $money;
                $dayAccrual->invest = $money;
                $dayAccrual->createTime = $now;
                $dayAccrual->updateTime = $now;
                $dayAccrual->sendID = $send->id;
                $dayAccrual->sendUserID = $userID;
                $accrual_result  = $dayAccrual->save();
                if(!$accrual_result) return $error;
                //钱包明细
                $rec_wallet = new UserWalletLog();
                $rec_wallet->type = 8;
                $rec_wallet->money = $money;
                $rec_wallet->createTime = $now;
                $rec_wallet->userID = $rec_info['id'];
                $rec_wallet->road = 1;
                $rec_wallet->desc = '新用户'.CommonFunction::dealTel($userInfo['tel']).'领取红包奖励';
                $rec_wallet_result = $rec_wallet->save();
                if(!$rec_wallet_result) return $error;

                $team_brokerage = new TeamBrokerage();
                $team_brokerage->investID = 0;
                $team_brokerage->productID = 0;
                $team_brokerage->userID = $rec_info['id'];
                $team_brokerage->investUserID = $userID;
                $team_brokerage->money = 0;
                $team_brokerage->brokerage = $money;
                $team_brokerage->rate = 0;
                $team_brokerage->createTime = $now;
                $team_brokerage->userInvestID = 0;
                $brokerage_result = $team_brokerage->save();
                if(!$brokerage_result) return $error;
                if(!empty($rec_info['openID'])){
                    SendWxMessage::hongbao($rec_info['openID'], '-'.CommonFunction::formatMoney($money).'元', '您的好友'.CommonFunction::dealTel($userInfo['tel']).'领取了您的'.CommonFunction::formatMoney($money).'元红包。');
                    SendWxMessage::charge($rec_info['openID'], CommonFunction::formatMoney($money), '您的好友'.CommonFunction::dealTel($userInfo['tel']).'注册，您获得了'.CommonFunction::formatMoney($money).'元！');
                }
            }
        }*/

        if(!empty($userInfo['openID'])){
            $result = BindService::team($userInfo);
            if(!$result)
                return $error;
            SendWxMessage::charge($userInfo['openID'], CommonFunction::formatMoney($money), '您领取了'.CommonFunction::formatMoney($money).'元红包！');
        }
        return ['status'=>1];
    }

    //领取红包动作
    public static function get($userInfo, $id, $bind = false){
        $error['status'] = 0;
        $error['msg'] = UserMsg::$time_out;
        $userID = $userInfo['userID'];
        $send = HongbaoSend::findOne($id);
        if(!$send) return $error;
        //$result['list'] = HongbaoSendList::find()->where(['sendUserID'=>$userID])->asArray()->all();
        $status = HongbaoSendList::findOne(['userID'=>$userID, 'sendID'=>$id]);

        if($status){
            $error['msg'] = UserMsg::$alread_hongbao;
            return $error;
        }
        if(intval($send->use) >= $send->amount){
            $error['msg'] = UserMsg::$over_hongbao;
            return $error;
        }
        $now = time();
        $send->use = intval($send->use) + 1;
        $send_result = $send->save();
        if(!$send_result) return $error;
        $sendList_model = new HongbaoSendList();
        $sendList_model->sendID = $send->id;
        $sendList_model->sendUserID = $send->userID;
        $sendList_model->money = $send->money;
        $sendList_model->userID = $userID;
        $sendList_model->createTime = $now;
        $sendList_result = $sendList_model->save();
        if(!$sendList_result) return $error;
        $_money = CommonFunction::formatMoney($send['money']);
        $recInfo = User::findOne($send->userID);
        if($recInfo['openID'])
            SendWxMessage::hongbao($recInfo['openID'], '-'.$_money.'元', '您的好友'.CommonFunction::dealTel($userInfo['tel']).'领取了您的'.$_money.'元红包。');
        $hb_result = HongBaoService::add($userInfo, $send['money'], 0, 0, '您领取了'.$_money.'元现金红包。', $send->id);
        if(!empty($userInfo['openID']) && $bind) {
            $result = BindService::team($userInfo);
            if (!$result)
                return $error;
        }
        if($hb_result)
            return ['status'=>1];
        else
            return $error;

    }

}